package com.weipai.springboot.module.service.impl;

import com.weipai.springboot.enums.RetCode;
import com.weipai.springboot.model.*;
import com.weipai.springboot.model.api.Response;
import com.weipai.springboot.module.dao.CenterDao;
import com.weipai.springboot.module.mapper.*;
import com.weipai.springboot.module.service.CenterService;
import com.weipai.springboot.module.util.SessionUserUtil;
import com.weipai.springboot.util.HttpClientUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @Author: 曹朋飞
 * @Date: 2018/08/23 17:49
 */
@Service
public class CenterServiceImpl implements CenterService{

    private static final Logger log = LoggerFactory.getLogger(CenterServiceImpl.class);

    @Autowired
    private CenterDao centerDao;
    @Autowired
    private SessionUserUtil sessionUserUtil;
    @Autowired
    ShopMapper shopMapper;
    @Autowired
    CustomerMapper customerMapper;
    @Autowired
    CustomerCategoryMapper customerCategoryMapper;
    @Autowired
    BankMapper bankMapper;
    @Autowired
    GoodsCollectionMapper goodsCollectionMapper;
    @Autowired
    ShopCollectionMapper shopCollectionMapper;
    @Autowired
    CustomerFootprintMapper customerFootprintMapper;
    @Autowired
    CustomerAddressMapper customerAddressMapper;
    @Autowired
    CustomerInvoiceMapper customerInvoiceMapper;
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    CustomerBankMapper customerBankMapper;


    //获取用户的收货地址
    @Override
    public Response getAddressByCustomerId(String id) {
        Response response = new Response();
        List<CustomerAddress> addresses = centerDao.getAddressByCustomerId(id);
        if(addresses.size()>0){
            response.setCode(RetCode.SUCCESS);
            response.put("data",addresses);
        }else{
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }

    //获取收货地址详细信息
    @Override
    public Response getAddressInfoById(String id) {
        Response response = new Response();
        CustomerAddress address = centerDao.getAddressInfoById(id);
        if(null!=address){
            response.setCode(RetCode.SUCCESS);
            response.put("address",address);
        }else{
            log.debug("未获取到地址信息:{}",id);
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //新增收货地址
    @Override
    @Transactional(readOnly=false, propagation = Propagation.REQUIRED)
    public Response saveAddress(CustomerAddress address) {
        Response response = new Response();
        address.setAdressDel(0);
        //验证是否有默认地址
        CustomerAddress customerAddress = customerAddressMapper.varCustomerAddress(address.getCustomerId());
        if(customerAddress!=null && address.getIsDefault()==1){
            customerAddress.setIsDefault(0);
            customerAddressMapper.updateByPrimaryKeySelective(customerAddress);
        }
        if(centerDao.saveAddress(address)==1){
            response.setCode(RetCode.SUCCESS);
        }else{
            log.debug("保存收货地址失败:{}");
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //删除收货地址
    @Override
    public Response deleteAddressById(String id) {
        Response response = new Response();

        CustomerAddress customerAddress = customerAddressMapper.selectByPrimaryKey(id);
        if(null != customerAddress){
            customerAddress.setAdressDel(-1);
            customerAddressMapper.updateByPrimaryKeySelective(customerAddress);
            response.setCode(RetCode.SUCCESS);
            return response;
        }else{
            response.setCode(RetCode.NO_DATA);
            return response;
        }
    }

    //新增银行卡
    @Override
    public Response saveBank(CustomerBank customerBank, String newCode, String oldCode) {
        Response response = new Response();
        if(null==newCode || null==oldCode){
            response.put("code",401);
            response.put("msg","请输入验证码");
            return response;
        }
        if(!newCode.equals(oldCode)){
            response.put("code",401);
            response.put("msg","验证码输入有误，请重新输入");
            return response;
        }
        //通过银行卡号,验证是否添加过此卡
        if(customerBank.getBankCard()!=null&&customerBank.getBankCard()!=""){
            CustomerBank customerBank1 = customerBankMapper.getBankByBankCard(customerBank.getBankCard());
            if(customerBank1!=null){
                response.setCode(RetCode.VAR_BANK);
                return response;
            }else{
                String customerId = sessionUserUtil.getUserAttr().getCustomerId();
                customerBank.setCustomerId(customerId);
                if(centerDao.saveBank(customerBank)==1){
                    response.setCode(RetCode.SUCCESS);
                }else{
                    log.debug("保存银行卡失败:{}");
                    response.setCode(RetCode.REQUEST_ERROR);
                }
            }
        }
        return response;
    }

    //获取用户的银行卡
    @Override
    public Response getBankByCustomerId(String id) {
        Response response = new Response();
        List<CustomerBank> banks = centerDao.getBankByCustomerId(id);
        if(banks.size()>0){
            response.setCode(RetCode.SUCCESS);
            response.put("data",banks);
        }else{
            response.setCode(RetCode.NO_DATA);
        }
        return response;
    }

    //删除银行卡
    @Override
    public Response deleteBankById(String id) {
        Response response = new Response();
        if(centerDao.deleteBankById(id)==1){
            response.setCode(RetCode.SUCCESS);
        }else{
            log.debug("删除银行卡失败:{}",id);
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //绑定支付宝账号
    @Override
    public Response bindingAlipayAccount(String alipayAccount, String realName) {
        Response response = new Response();
        String customerId = sessionUserUtil.getUserAttr().getCustomerId();
        if(centerDao.bindingAlipayAccount(customerId, alipayAccount, realName)==1){
            response.setCode(RetCode.SUCCESS);
        }else{
            log.debug("绑定支付宝账号失败，用户id:{}",alipayAccount);
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //修改收货地址
    @Override
    @Transactional(readOnly=false, propagation = Propagation.REQUIRED)
    public Response updateAddress(CustomerAddress address) {
        Response response = new Response();

        //验证是否有默认地址
        CustomerAddress customerAddress = customerAddressMapper.varCustomerAddress(address.getCustomerId());
        if(customerAddress!=null && address.getIsDefault()==1){
            customerAddress.setIsDefault(0);
            customerAddressMapper.updateByPrimaryKeySelective(customerAddress);
        }
        if(centerDao.updateAddress(address)==1){
            response.setCode(RetCode.SUCCESS);
        }else{
            log.debug("修改地址失败:{}",address.getAddressId());
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //新增发票
    @Override
    @Transactional(readOnly=false, propagation = Propagation.REQUIRED)
    public Response saveInvoice(CustomerInvoice customerInvoice) {
        Response response = new Response();

        //验证是否有默认发票
        CustomerInvoice customerInvoice22  = customerInvoiceMapper.varCustomerInvoice(customerInvoice.getCustomerId());
        if(customerInvoice22!=null && customerInvoice.getIsDefault()==1){
            customerInvoice22.setIsDefault(0);
            customerInvoiceMapper.updateByPrimaryKeySelective(customerInvoice22);
        }

        if(centerDao.saveInvoice(customerInvoice)==1){
            response.setCode(RetCode.SUCCESS);
            response.setData(customerInvoice);
        }else{
            log.debug("保存发票失败:{}");
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //修改发票
    @Override
    @Transactional(readOnly=false, propagation = Propagation.REQUIRED)
    public Response updateInvoice(CustomerInvoice customerInvoice) {
        Response response = new Response();
        //验证是否有默认发票
        CustomerInvoice customerInvoice22  = customerInvoiceMapper.varCustomerInvoice(customerInvoice.getCustomerId());
        if(customerInvoice22!=null && customerInvoice.getIsDefault()==1){
            customerInvoice22.setIsDefault(0);
            customerInvoiceMapper.updateByPrimaryKeySelective(customerInvoice22);
        }
        if(customerInvoiceMapper.updateByPrimaryKeySelective(customerInvoice)==1){
            response.setCode(RetCode.SUCCESS);
        }else{
            log.debug("更改发票失败:{}");
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //获取用户的发票
    @Override
    public Response invoiceList(String customerId) {
        Response response = new Response();
        //获得用户 id
           List<CustomerInvoice> banks = centerDao.invoiceList(customerId);
            if(banks.size()>0){
                response.setCode(RetCode.SUCCESS);
                response.put("list",banks);
            }else{
                response.setCode(RetCode.NO_DATA);
            }
        return response;
    }

    //删除发票信息
    @Override
    public Response deleteInvoiceById(String id) {
        Response response = new Response();
        if(centerDao.deleteInvoiceById(id)==1){
            response.setCode(RetCode.SUCCESS);
        }else{
            log.debug("删除发票信息失败:{}",id);
            response.setCode(RetCode.REQUEST_ERROR);
        }
        return response;
    }

    //获取支付宝账号详细信息
    @Override
    public Response getAlipayAccountCustomerId() {
        Response response = new Response();
        String customerId = sessionUserUtil.getUserAttr().getCustomerId();
        Map<String, Object> map = centerDao.getAlipayAccountCustomerId(customerId);
        if(map!=null && map.size()>0){
            response.setCode(RetCode.SUCCESS);
            response.setData(map);
        }else{
            log.debug("未获取到支付宝账号id{}",customerId);
            response.setCode(RetCode.ALIPAY_NO);
        }
        return response;
    }

    //设置地址为默认收货地址
    @Override
    public Response isDefaultAddress(String id) {
        return null;
    }


    //获取个人中心信息
    @Override
    public Response getCenterById(String customerId) {
        Response response = new Response();
        if(customerId!=null && customerId!="") {
            //商品收藏
            List<GoodsCollection> goodsCollectionList = goodsCollectionMapper.selectAllByGoodsCollection(customerId, 0, 99999);
            Integer goodsCollectionNum = goodsCollectionList.size();
            //店铺收藏
            List<ShopCollection> shopCollectionList = shopCollectionMapper.selectAllByShopCollection(customerId, 0, 99999);
            Integer shopCollectionNum = shopCollectionList.size();
            //我的足迹
            List<Map<String, Object>> customerFootprintList = customerFootprintMapper.selectAllByCustomerFootprint(customerId, 0, 99999);
            Integer customerFootprintNum = customerFootprintList.size();
            //获得客户信息
            Customer customer = customerMapper.getCustomerById(customerId);
            //获取 会员等级
            Map<String, Object> map = customerMapper.getCenterCustomerById(customerId);
            Shop shop = shopMapper.getShopByCustomerId(customerId);
            //获取各个不同状态订单 数量
            List<Map<String, Object>>  listByNum =  orderMapper.getOrderCountListByNum(customerId);
            Integer size = listByNum.size();
            //待付款数量 1
            Integer noPay=0;
            //待发货数量 2
            Integer noSend =0;
            //待收货数量 3
            Integer noReceived =0;
            //生成中数量 6
            Integer productionNum=0;
            for (int i = 0; i <size ; i++) {
                if (listByNum.get(i).get("orderStatus").equals("1")){
                    noPay = Integer.parseInt(listByNum.get(i).get("count").toString());
                }
                if (listByNum.get(i).get("orderStatus").equals("2")){
                    noSend = Integer.parseInt(listByNum.get(i).get("count").toString());
                }
                if (listByNum.get(i).get("orderStatus").equals("3")){
                    noReceived = Integer.parseInt(listByNum.get(i).get("count").toString());
                }
                if (listByNum.get(i).get("orderStatus").equals("6")){
                    productionNum = Integer.parseInt(listByNum.get(i).get("count").toString());
                }
            }
            if (shop != null) {
                //获得店铺信息----------更新消息
                response.put("shopStatus",shop.getShopStatus());       //店铺状态：0：运营，-1：停止运营',
                response.put("customer", customer);
                response.put("memberLevelName", map.get("memberLevelName"));
                response.put("adminCode", customer.getAdminCode());
                response.put("applicantStatus", shop.getApplicantStatus());//店铺状态
                response.put("goodsNumber", goodsCollectionNum);//商品收藏
                response.put("collectionNumber", shopCollectionNum);//店铺收藏
                response.put("shopDel", customerFootprintNum);//我的足迹
                response.put("shopId", shop.getShopId());//shopId
                response.put("noPay", noPay);//待付款数量
                response.put("noSend", noSend);//待发货数量
                response.put("noReceived", noReceived);//待收货数量
                response.put("productionNum", productionNum);//生产中 数量
                response.setCode(RetCode.SUCCESS);
            } else {
                response.put("shopStatus",-2);        //店铺状态：0：运营，-1：停止运营',  -2 :无店铺
                response.put("customer", customer);
                response.put("memberLevelName", map.get("memberLevelName"));
                response.put("adminCode", customer.getAdminCode());
                response.put("applicantStatus", -1);//暂无店铺
                response.put("goodsNumber", goodsCollectionNum);//商品收藏
                response.put("collectionNumber", shopCollectionNum);//店铺收藏
                response.put("shopDel", customerFootprintNum);//我的足迹
                response.put("shopId", "");//shopId
                response.put("noPay", noPay);//待付款数量
                response.put("noSend", noSend);//待发货数量
                response.put("noReceived", noReceived);//待收货数量
                response.put("productionNum", productionNum);//生产中 数量
                response.setCode(RetCode.SUCCESS);
            }
        }else {
            response.setCode(RetCode.NOT_LOGIN);
        }
        return response;
    }

    //根据  用户传的 银行卡号  返回是那个银行的卡, 银行logo
    @Override
    public Response getBankBybankCard(String bankCard) {
        Response response = new Response();
        try {
            Map<String, Object> map = HttpClientUtils.getJson("https://ccdcapi.alipay.com/validateAndCacheCardInfo.json?_input_charset=utf-8&cardNo="+bankCard+"&cardBinCheck=true", Map.class);
            //从map中 取 bank=CCB,  对应 银行缩写
            String bankAbbr = String.valueOf(map.get("bank"));
            Bank bank = bankMapper.selectByBankAbbr(bankAbbr);
            if(bank!=null){
                response.put("bank",bank);
                response.setCode(RetCode.SUCCESS);
            }else {
                response.setCode(RetCode.NO_DATA);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response;
    }

}
